package com.woniu.after.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.after.entity.TOrderAfter;
import com.woniu.after.entity.dto.*;
import com.woniu.after.feign.OrderFeignListener;
import com.woniu.after.service.TOrderAfterService;
import com.woniu.after.mapper.TOrderAfterMapper;
import com.woniu.after.service.TOrderExpressService;
import com.woniu.common.dto.OrderAfterQMoneyDto;
import com.woniu.common.util.PageParam;
import com.woniu.common.util.ResponseData;
import org.checkerframework.checker.regex.qual.PolyRegex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;

/**
 * @author Kenneon
 * @description 针对表【t_order_after】的数据库操作Service实现
 * @createDate 2024-05-24 14:25:32
 */
@Service
public class TOrderAfterServiceImpl extends ServiceImpl<TOrderAfterMapper, TOrderAfter>
        implements TOrderAfterService {
    @Autowired
    TOrderAfterMapper tOrderAfterMapper;
    @Autowired
    private TOrderAfterService tOrderAfterService;
    @Autowired
    private OrderFeignListener orderFeignListener;
    @Autowired
    private TOrderExpressService tOrderExpressService;
    @Autowired
    private HttpServletResponse response;

    @Value("${snowflake.workId}")
    private long workId;
    @Value("${snowflake.datacenterId}")
    private long datacenterId;

    @Override
    public IPage<OrderAfterDto> queryAllAfterOrderInfo(Page<?> page, PageInfoDto pageInfoDto) {
        OrderAfterDto orderAfterDto = pageInfoDto.getOrderAfterDto();
        String afterNumString = String.valueOf(orderAfterDto.getAfterNum());
        String detailNumString = String.valueOf(orderAfterDto.getDetailNum());
        orderAfterDto.setDetailNumS(detailNumString);
        orderAfterDto.setAfterNumS(afterNumString);
        IPage<OrderAfterDto> orderAfterDtoIPage = tOrderAfterMapper.queryAfterInfo(page, orderAfterDto);
        List<OrderAfterDto> records = orderAfterDtoIPage.getRecords();
        for (OrderAfterDto record : records) {
            record.setAfterNumS(record.getAfterNum().toString());
            record.setDetailNumS(record.getDetailNum().toString());
        }
        return orderAfterDtoIPage;
    }

    @Override
    public void createAfterOrder(List<TOrderAfter> orderAfterDto) {
        List<TOrderAfter> allOrderAfterRecords = new ArrayList<>();

//        设置TypId
        OrderAfterQMoneyDto orderAfterQMoneyDto2 = new OrderAfterQMoneyDto();


        for (TOrderAfter tOrderAfter : orderAfterDto) {
            long orderId = IdUtil.getSnowflake(workId, datacenterId).nextId();
            OrderAfterQMoneyDto orderAfterQMoneyDto1 = new OrderAfterQMoneyDto();
            orderAfterQMoneyDto1.setSelectAll(tOrderAfter.getSelectAll());
            orderAfterQMoneyDto1.setOrderNum(tOrderAfter.getOrderNum());
            orderAfterQMoneyDto1.setSelectAll(tOrderAfter.getSelectAll());
            orderAfterQMoneyDto2.setAfterTypeId(tOrderAfter.getAfterTypeId());
            orderAfterQMoneyDto1.setUserId(tOrderAfter.getUserId());
            orderAfterQMoneyDto1.setReason(tOrderAfter.getReason());
            if (tOrderAfter.getSelectAll() == 2) {
                List<Long> detailNums = tOrderAfter.getDetailNums();
                if (detailNums == null || detailNums.isEmpty()) {
                    continue;
                }
                orderAfterQMoneyDto1.setDetailNums(detailNums);
            }

            List<OrderAfterQMoneyDto> orderAfterQMoneyDtos = tOrderAfterMapper.queryOrderAfterMoney(orderAfterQMoneyDto1);

            if (orderAfterQMoneyDtos != null && !orderAfterQMoneyDtos.isEmpty()) {
                for (OrderAfterQMoneyDto orderAfterQMoneyDto : orderAfterQMoneyDtos) {
                    TOrderAfter newOrderAfter = new TOrderAfter();
                    newOrderAfter.setAfterNum(orderId);
                    newOrderAfter.setDetailNum(orderAfterQMoneyDto.getDetailNum());
                    if (tOrderAfter.getSelectAll() == 2) {
                        List<Long> detailNums = new ArrayList<>();

                        System.err.println(orderAfterQMoneyDto.getDetailNum());
                        detailNums.add(orderAfterQMoneyDto.getDetailNum());
                        if (detailNums != null) {
                            for (Long detailNum : detailNums) {
                                TOrderAfter detailOrderAfter = new TOrderAfter();
                                detailOrderAfter.setAfterNum(orderId);
                                detailOrderAfter.setDetailNum(detailNum);
                                detailOrderAfter.setPrice(orderAfterQMoneyDto.getPayMoney());
                                detailOrderAfter.setProductSkuId(orderAfterQMoneyDto.getItemId());
                                detailOrderAfter.setOrderNum(orderAfterQMoneyDto.getOrderNum());
                                detailOrderAfter.setAfterTypeId(orderAfterQMoneyDto2.getAfterTypeId());
                                detailOrderAfter.setUserId(orderAfterQMoneyDto1.getUserId());
                                detailOrderAfter.setStatus("1");
                                detailOrderAfter.setReason(orderAfterQMoneyDto1.getReason());
                                allOrderAfterRecords.add(detailOrderAfter);
                            }
                        }
                    } else {
                        newOrderAfter.setPrice(orderAfterQMoneyDto.getPayMoney());
                        newOrderAfter.setProductSkuId(orderAfterQMoneyDto.getItemId());
                        newOrderAfter.setOrderNum(orderAfterQMoneyDto.getOrderNum());
                        newOrderAfter.setStatus("1");
                        allOrderAfterRecords.add(newOrderAfter);
                    }
                }
            }
        }
        try {
            tOrderAfterService.saveBatch(allOrderAfterRecords);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public OrderAfterDetailDto queryAfterDetailInfo(Long detailNum) {
        return tOrderAfterMapper.queryOrderAfterDetail(detailNum);

    }

    @Override
    public OrderNumberDetailDto queryByAfterNum(Long afterNum) {
        return tOrderAfterMapper.queryByAfterNum(afterNum);


    }

    @Override
    public void changeAfterNumStatus(Long detailNum) {
        TOrderAfter one = tOrderAfterService.query().eq("detail_num", detailNum).one();
        if (one.getAfterTypeId() == 2) {
            tOrderExpressService.addExpress(detailNum);
//            向物流表内插入数据
            tOrderAfterService.update().eq("detail_num", detailNum).set("status", 2).update();

        } else {
//            退款成功
            orderFeignListener.refund(detailNum.toString());
            tOrderAfterService.update().eq("detail_num", detailNum).set("status", 2).update();
        }
    }

    @Override
    public void exprotAfterExcel(List<String> detailNums, HttpServletResponse response) {
        try {
            String fileName = "售后信息.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            List<String> detailNumList = new ArrayList<>();

            for (String detailNum : detailNums) {
                String detaiNum = detailNum.toString();
                detailNumList.add(detaiNum);
            }
            List<OrderAfterExcelDto> orderAfterExcelDtos = tOrderAfterMapper.exportAfterExcel(detailNumList);


            EasyExcel.write(response.getOutputStream(), OrderAfterExcelDto.class).sheet("afterOrder")
                    .doWrite(orderAfterExcelDtos);
        } catch (Exception e) {
            log.error("导出 Excel 文件时出现错误：" + e.getMessage());
        }
    }
}




